//
//  RegisterVC.swift
//  kxf
//
//  Created by Mac on 2024/3/4.
//

import Foundation
import UIKit
import MCToast

class RegisterVC: WHBaseViewVC {
    
    var getCodeTime = 60
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
    }
    
    lazy var whiteView : UIView = {
        let vi = UIView.init(frame: CGRect.init(x: 0, y: getNavigationBarHeight()+kFitWidth(10), width: SCREEN_WIDHT, height: RegisterViewHeadTitleVM().selfHeight+RegisterInputVM().selfHeight*5))
        vi.backgroundColor = .white
        vi.isUserInteractionEnabled = true
        vi.layer.cornerRadius = kFitWidth(8)
        
        return vi
    }()
    lazy var titleVm : RegisterViewHeadTitleVM = {
        let vm = RegisterViewHeadTitleVM.init(frame: CGRect.init(x: 0, y: 0, width: 0, height: 0))
        vm.titleLabel.text = "用户信息"
        return vm
    }()
    lazy var phoneVm : RegisterInputVM = {
        let vm = RegisterInputVM.init(frame: CGRect.init(x: 0, y: RegisterViewHeadTitleVM().selfHeight, width: 0, height: 0))
        vm.leftLabel.text = "+86"
        vm.textField.placeholder = "请输入您的手机号"
        vm.maxLength = 11
        vm.textField.keyboardType = .numberPad
        return vm
    }()
    lazy var codeVm : RegisterInputVM = {
        let vm = RegisterInputVM.init(frame: CGRect.init(x: 0, y: self.phoneVm.frame.maxY, width: 0, height: 0))
        vm.leftLabel.text = "验证码"
        vm.textField.placeholder = "请输入验证码"
        vm.showCodeBtn()
        vm.maxLength = 6
        vm.getCodeBlock = {()in
            self.getCodeRequest()
        }
        
        return vm
    }()
    lazy var pswVm : RegisterInputVM = {
        let vm = RegisterInputVM.init(frame: CGRect.init(x: 0, y: self.codeVm.frame.maxY, width: 0, height: 0))
        vm.leftLabel.text = "密码"
        vm.textField.placeholder = "请输入密码"
        
        return vm
    }()
    lazy var pswConfirmVm : RegisterInputVM = {
        let vm = RegisterInputVM.init(frame: CGRect.init(x: 0, y: self.pswVm.frame.maxY, width: 0, height: 0))
        vm.leftLabel.text = "确认密码"
        vm.textField.placeholder = "请输入密码"
        
        return vm
    }()
    lazy var inviteCodeVm : RegisterInputVM = {
        let vm = RegisterInputVM.init(frame: CGRect.init(x: 0, y: self.pswConfirmVm.frame.maxY, width: 0, height: 0))
        vm.leftLabel.text = "邀请码"
        vm.textField.placeholder = "请输入邀请码"
        vm.maxLength = 6
        
        return vm
    }()
    
    lazy var registerBtn : UIButton = {
        let btn = UIButton()
        btn.setTitle("注册", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.layer.cornerRadius = kFitWidth(24)
        btn.clipsToBounds = true
        btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .regular)
        btn.backgroundColor = .THEME
        
        btn.addTarget(self, action: #selector(registAction), for: .touchUpInside)
        
        return btn
    }()
    
    lazy var protocalVm : ProtocalVM = {
        let vm = ProtocalVM.init(frame: CGRect.init(x: 0, y: self.whiteView.frame.maxY + kFitWidth(110), width: 0, height: 0))
        vm.backgroundColor = .clear
        vm.controller = self
        return vm
    }()
}

extension RegisterVC{
    @objc func registAction() {
        if checkValue(){
            sendRegisterRequest()
        }
    }
    func checkValue() -> Bool {
        if !judgePhoneNumber(phoneNum: phoneVm.textField.text){
            MCToast.mc_text("请输入正确的手机号")
            return false
        }
        if codeVm.textField.text?.count ?? 0 < 4{
            MCToast.mc_text("请输入正确的验证码")
            return false
        }
        if pswVm.textField.text?.count  ?? 0 < 6{
            MCToast.mc_text("密码不能少于6位")
            return false
        }
        if pswVm.textField.text != pswConfirmVm.textField.text {
            MCToast.mc_text("密码输入不一致")
            return false
        }
        if inviteCodeVm.textField.text?.count  ?? 0 < 3{
            MCToast.mc_text("请输入邀请码")
            return false
        }
        if protocalVm.isAgree == false{
            if UserModel.shared.isCheck == true{
                MCToast.mc_text("请阅读并同意《隐私政策》")
            }else{
                MCToast.mc_text("请阅读并同意《隐私政策》及《展业规范》")
            }
            return false
        }
        
        return true
    }
}
extension RegisterVC{
    func initUI() {
        initNavi(titleStr: "用户注册")
        
        view.backgroundColor = .COLOR_LIGHT_GREY
        
        view.addSubview(whiteView)
        whiteView.addSubview(titleVm)
        whiteView.addSubview(phoneVm)
        whiteView.addSubview(codeVm)
        whiteView.addSubview(pswVm)
        whiteView.addSubview(pswConfirmVm)
        whiteView.addSubview(inviteCodeVm)
        
        view.addSubview(registerBtn)
        view.addSubview(protocalVm)
        
        setConstrait()
    }
    
    func setConstrait() {
        registerBtn.snp.makeConstraints { make in
            make.centerX.lessThanOrEqualToSuperview()
            make.width.equalTo(kFitWidth(260))
            make.height.equalTo(kFitWidth(48))
            make.top.equalTo(whiteView.snp.bottom).offset(kFitWidth(37))
        }
    }
}

extension RegisterVC{
    @objc func getCodeRequest() {
        if !WHBaseViewVC().judgePhoneNumber(phoneNum: phoneVm.textField.text ?? ""){
            MCToast.mc_text("请输入正确的手机号")
            return
        }
        MCToast.mc_loading()
        self.codeVm.getCodeBtn.isUserInteractionEnabled = false
        let urlString = "\(URL_get_code)?phone=\(phoneVm.textField.text ?? "")&type=4"
        WHNetworkUtil.shareManager().GET(urlString: urlString,vc:self) { responseObject in
            DLLog(message: "getCodeRequest：\(responseObject)")
            
            MCToast.mc_text("验证码发送成功")
            let codeTimer = DispatchSource.makeTimerSource(flags: .init(rawValue: 0), queue: .global())
            codeTimer.schedule(deadline: .now(), repeating: .milliseconds(1000))
            codeTimer.setEventHandler {
                self.getCodeTime = self.getCodeTime - 1
                
                if self.getCodeTime < 0{
                    codeTimer.cancel()
                    self.getCodeTime = 60
                    DispatchQueue.main.async {
                        self.codeVm.getCodeBtn.isUserInteractionEnabled = true
                        self.codeVm.getCodeBtn.setTitle("获取验证码", for: .normal)
                    }
                }else{
                    DispatchQueue.main.async {
                        self.codeVm.getCodeBtn.isUserInteractionEnabled = false
                        self.codeVm.getCodeBtn.setTitle("\(self.getCodeTime) 秒", for: .normal)
                    }
                }
            }
            if #available(iOS 10.0, *) {
                codeTimer.activate()
            } else {
                codeTimer.resume()
            }
        }
    }
    func sendRegisterRequest() {
        MCToast.mc_loading()
        let param:[String:Any] = ["phone":"\(phoneVm.textField.text ?? "")",
                                  "verifyCode":"\(codeVm.textField.text ?? "")",
                                  "inviteCode":"\(inviteCodeVm.textField.text ?? "")",
                                  "password":"\(pswVm.textField.text ?? "")"]
        WHNetworkUtil.shareManager().POST(urlString: URL_register, parameters: param  as [String : AnyObject],isNeedToast: true,vc: self) { responseObject in
            DLLog(message: "\(responseObject)")
            
            self.presentAlertVc(confirmBtn: "确定", message: "您的账号已注册成功，请妥善保管您的账号密码。", title: "温馨提示", cancelBtn: nil, handler: { action in
                self.backTapAction()
            }, viewController: self)
        }
    }
}

